﻿using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Charades.Web.Helpers;

namespace Charades.Web.Controllers
{
	using System.IO;
	using System.Net.Mail;
	using System.Threading.Tasks;

	using CaptchaMvc.HtmlHelpers;

	using Charades.Web.Models;

	public class HomeController : Controller
	{
		private readonly string _rootUrl = ConfigurationManager.AppSettings["RootUrl"];

		public ActionResult Index()
		{
			return View();
		}

		[AjaxOnly]
		public ActionResult Notsupport()
		{
			return View();
		}

		[AjaxOnly]
		public ActionResult Logon()
		{
			return View();
		}

		[AjaxOnly]
		public ActionResult Intro()
		{
			return View();
		}

		[AjaxOnly]
		public ActionResult Game()
		{
			return View();
		}

		public ActionResult About()
		{
			return View();
		}

		[HttpPost]
		public ActionResult About(FeedbackViewModel model)
		{
			if (ModelState.IsValid && this.IsCaptchaValid("Captcha error"))
			{
				var t = new Task(
					() =>
					{
						using (var smtpClient = new SmtpClient("relay2.skydreams.ws"))
						{
							var mail = new MailMessage();

							mail.From = new MailAddress(model.Email);
							mail.To.Add("artskf@gmail.com");
							mail.Subject = "drawpi.co feedback";
							mail.Body = model.Content;

							smtpClient.Port = 2525;
							smtpClient.Credentials = new System.Net.NetworkCredential("", "");
							smtpClient.UseDefaultCredentials = false;
							smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

							smtpClient.Send(mail);
						}
					});

				t.Start();

				ViewBag.Message = "Ваше сообщение отправлено";

				return View();
			}
			return View(model);
		}

		public JsonResult UploadImage(string imageData, string name)
		{
			try
			{
				var targetFolder = HttpContext.Server.MapPath("~/pic");
				var targetPath = Path.Combine(targetFolder, name + ".png");
				var fileInfo = new FileInfo(targetPath);

				if (fileInfo.Exists && fileInfo.Length == 0)
				{
					var task = new Task(() =>
										{
											var ms = new MemoryStream(Convert.FromBase64String(imageData));
											var image = Image.FromStream(ms);

											var drawFormat = new StringFormat
															 {
																 Alignment = StringAlignment.Center,
																 FormatFlags = StringFormatFlags.NoWrap
															 };

											var graphic = Graphics.FromImage(image);

											var rectagleBrush = new SolidBrush(Color.FromArgb(50, Color.Black));
											graphic.FillRectangle(rectagleBrush, new Rectangle(430, 485, 70, 15));

											var textBrush = new SolidBrush(Color.White);
											var textFont = new Font("Verdana", 9, FontStyle.Bold);
											graphic.DrawString("drawpi.co", textFont, textBrush, 465, 485, drawFormat);

											image.Save(targetPath, ImageFormat.Png);

											rectagleBrush.Dispose();
											textBrush.Dispose();
											textFont.Dispose();
											drawFormat.Dispose();
											graphic.Dispose();
											image.Dispose();
											ms.Dispose();
										});

					task.Start();
				}
				else
				{
					return Json(new { success = false });
				}
			}
			catch
			{
				return Json(new { success = false });
			}

			return Json(new { success = true, url = string.Format("{0}/{1}", _rootUrl, new string(name.Take(8).ToArray())) });
		}

		public ActionResult Picture(string id)
		{
			var model = new PictureModel();
			var targetFolder = HttpContext.Server.MapPath("~/pic");
			var files = Directory.GetFiles(targetFolder, id + "*");

			if (files.Length > 0)
			{
				var fileInfo = new FileInfo(files[0]);

				model.PictureUrl = string.Format("{0}/pic/{1}", _rootUrl, fileInfo.Name);
				model.FileIsReady = fileInfo.Length > 0;

				var fileData = Base32Hepler.DecodeFrom32(
					fileInfo.Name.Replace(id, string.Empty)
								.Replace(fileInfo.Extension, string.Empty)
				).Split(' ').ToArray();

				model.Painter = fileData[0];
				model.Word = fileData[1];
			}
			else
			{
				throw new HttpException(404, "Page not found");
			}

			return View(model);
		}

		public ActionResult Contact()
		{
			ViewBag.Message = "Your contact page.";

			return View();
		}

		public ActionResult Feed()
		{
			var targetFolder = HttpContext.Server.MapPath("~/pic");
			var files = Directory.GetFiles(targetFolder)
				.Select(x => new FileInfo(x)).Where(x => x.Name != "empty.png").OrderByDescending(x => x.LastWriteTimeUtc)
				.Select(
					fileInfo =>
					{
						var id = new string(fileInfo.Name.Take(8).ToArray());
						var fileData = Base32Hepler.DecodeFrom32(
							fileInfo.Name.Replace(id, string.Empty)
										.Replace(fileInfo.Extension, string.Empty)
						).Split(' ').ToArray();
						return new PictureModel()
									{
										Id = id,
										PictureUrl = string.Format("{0}/pic/{1}", _rootUrl, fileInfo.Name),
										Painter = fileData[0],
										Word = fileData[1]
									};
					})
				.ToList();
			return View(files);
		}
	}
}